﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Algorithms
{
    public class SortingCorrectnessAnalysis : IAnalyzeStrategy
    {
        private int[] _sampleData;

        public AnalyzeStrategyResult Execute(IAlgorithm algorithmToAnalyze)
        {
            IntegerGenerator intGen = new IntegerGenerator();
            _sampleData = intGen.GetRamdomInteger(1000);

            algorithmToAnalyze.Execute(_sampleData);

            AnalyzeStrategyResult aResult = new AnalyzeStrategyResult();
            aResult.StrategyName = this.ToString();

            if (ResultVerify())
            {
                aResult.Successful = true;
                aResult.Message = "Sorting executed correctly.";
            }
            else
            {
                aResult.Successful = false;
                aResult.Message = "Sorting order is not consistent.";
            }

            return aResult;
        }

        private bool ResultVerify()
        {
            long lDiff = _sampleData[1] - _sampleData[0];
            long rDiff = _sampleData[2] - _sampleData[1];

            bool vResult = false;

            if (lDiff >= 0 && rDiff >= 0)
            {
                vResult = Verifying(true);
            }
            else if (lDiff <= 0 && rDiff <= 0)
            {
                vResult = Verifying(false);
            }
            else
            {
                vResult = false;
            }

            return vResult;
        }

        private bool Verifying(bool isAscending)
        {
            for (int i = 1; i < _sampleData.Length - 1; i++)
            {
                long lDiff = _sampleData[i] - _sampleData[i - 1];
                long rDiff = _sampleData[i + 1] - _sampleData[i];

                if (isAscending)
                {
                    if (!(lDiff >= 0 && rDiff >= 0))
                    {
                        return false;
                    }
                }
                else
                {
                    if (!(lDiff <= 0 && rDiff <= 0))
                    {
                        return false;
                    }
                }
            }

            return true;
        }
    }
}
